package com.icss.head.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.icss.common.servlet.BaseServlet;
import com.icss.common.util.ConstatFinalUtil;
import com.icss.common.vo.ApiResponse;
import com.icss.common.vo.ApiResponseEnum;
import com.icss.service.IProductDbService;
import com.icss.service.IUsersDbService;
import com.icss.service.impl.ProductDbServiceImpl;
import com.icss.service.impl.UsersDbServiceImpl;
import com.icss.vo.MakeupBlog;
import com.icss.vo.MakeupBlogEnum;
import com.icss.vo.MakeupCart;
import com.icss.vo.MakeupUsers;

/**
 * 用户首页操作
 * 
 * @author 陈岩
 */
@WebServlet(urlPatterns = "/head/UsersHeadServlet")
public class UsersHeadServlet extends BaseServlet
{
	private IUsersDbService usersDbService;
	private IProductDbService productDbService;
	
	@Override
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
		this.productDbService = new ProductDbServiceImpl() ; 
		
		UsersDbServiceImpl usersDbServiceImpl = new UsersDbServiceImpl();
		usersDbServiceImpl.setProductDbService(productDbService);
		
		this.usersDbService = usersDbServiceImpl;
	}
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		/* 接收参数 */
		String method = request.getParameter("method");
		if ("main".equalsIgnoreCase(method))
		{
			/* main */
			main(request, response);
		} else if ("usersUpdateSubmit".equalsIgnoreCase(method))
		{
			/* usersUpdateSubmit */
			usersUpdateSubmit(request, response);
		}else if ("cartList".equalsIgnoreCase(method))
		{
			/* cartList */
			cartList(request, response);
		} else if ("cartInsertSubmit".equalsIgnoreCase(method))
		{
			/* cartInsertSubmit */
			cartInsertSubmit(request, response);
		}else if ("cartDelete".equalsIgnoreCase(method))
		{
			/* cartDelete */
			cartDelete(request, response);
		} else if ("logout".equalsIgnoreCase(method))
		{
			/* logout */
			logout(request, response);
		} else if ("blogInsert".equalsIgnoreCase(method))
		{
			/* blogInsert */
			blogInsert(request, response);
		} else if ("blogInsertSubmit".equalsIgnoreCase(method))
		{
			/* blogInsertSubmit */
			blogInsertSubmit(request, response);
		} else if ("blogUpdateSubmit".equalsIgnoreCase(method))
		{
			/* blogUpdateSubmit */
			blogUpdateSubmit(request, response);
		}
	}
	
	/**
	 * 首页
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void main(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		String path = "/head/users/main";
		/* 准备路径 */
		/* 从session中获取信息 */
		MakeupUsers users = (MakeupUsers) this.findObjfromSession(request, "users");
		int usersId = users.getId() ;
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", usersId);
		ApiResponse<MakeupUsers> apiResponse = this.usersDbService.findOneUsersService(condMap);
		if(this.updateFlag == null || "".equalsIgnoreCase(this.updateFlag))
		{
			/* 清空信息 */
			apiResponse.clearInfo();
		}
		request.setAttribute("response", apiResponse.toJSON());
		/* 根据不同的判断,页面跳转 */
		String operType = request.getParameter("operType");
		if("update".equalsIgnoreCase(operType))
		{
			/* 修改页面 */
			path = "/head/users/usersUpdate" ; 
		}
		
		path = this.prefix + path + this.subfix; 
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 更新
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void usersUpdateSubmit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		HttpSession session = request.getSession(); 
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 存储多个结果,Map存储 */
		Map<String, Object> dataMapJava = new HashMap<String, Object>();
		apiResponse.setDataMapJava(dataMapJava);
		
		/* 从session中获取信息 */
		MakeupUsers users = (MakeupUsers) this.findObjfromSession(request, "users");
		int usersId = users.getId() ;
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", usersId);
		ApiResponse<MakeupUsers> apiResponseRes = this.usersDbService.findOneUsersService(condMap);
		request.setAttribute("response", apiResponseRes.toJSON());
		
		users = apiResponseRes.getDataOneJava() ; 
		
		boolean updateFlag = false ; 
		/* 根据不同的判断,页面跳转 */
		String operType = request.getParameter("operType");
		if("update".equalsIgnoreCase(operType))
		{
			String email = request.getParameter("email");
			String nick = request.getParameter("nick");
			String addr = request.getParameter("addr");
			String phone = request.getParameter("phone");
			
			users.setEmail(email);
			users.setNick(nick);
			users.setAddr(addr);
			users.setPhone(phone);
			
			updateFlag = true ; 
		}
		
		/* 更新 */
		if(updateFlag)
		{
			apiResponse = this.usersDbService.updateOneUsersService(users);
			session.setAttribute("users", users);
		}
		apiResponse.setInfo(
				ConstatFinalUtil.INFO_JSON.getString(apiResponseRes.getCode() + ""),
				Collections.EMPTY_MAP);
		
		this.updateFlag = "true" ; 
		request.setAttribute("response", apiResponseRes.toJSON());
		this.main(request,response) ; 
	}
	
	/**
	 * 购物车列表
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void cartList(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		/* 准备路径 */
		MakeupUsers users = (MakeupUsers) this.findObjfromSession(request, "users");
		
		/* 分页信息 */
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		/* 查询我的,查询启用的购物车 */
		condMap.put("usersId", users.getId());
		condMap.put("extend", "true");
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		ApiResponse<MakeupCart> apiResponse = this.usersDbService.findCondListCartService(null, condMap);
		/* 将结果存储到Request中 */
		request.setAttribute("response", apiResponse.toJSON());
		
		/* 页面跳转 */
		String path =  "/head/users/cartList" ; 
		path = this.prefix + path + this.subfix; 
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 购物车添加提交
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void cartInsertSubmit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		MakeupUsers users = (MakeupUsers) this.findObjfromSession(request, "users");
		
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 准备路径 */
		try
		{
			/* 需要返回json */
			String proId = request.getParameter("proId");
			String num = request.getParameter("num");
			
			/* 创建对象 */
			MakeupCart cart = new MakeupCart();
			
			/* 赋值 */
			cart.setUsersId(users.getId());
			cart.setProdId(Integer.valueOf(proId));
			cart.setNum(Integer.valueOf(num));
			
			/* 保存数据库 */
			apiResponse = this.usersDbService.saveOneCartService(cart);
			request.setAttribute("response", apiResponse.toJSON());
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("添加购物车报错了;",e);
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		/* 成功,提示 */
		JSONObject resultJSON = apiResponse.toJSON();
		this.printOut(resultJSON.toJSONString(), response);
	}

	/**
	 * 购物车更新提交
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void cartDelete(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		Map<String, Object> condMap = new HashMap<String, Object>();
		
		/* 按照id查询 */
		String id = request.getParameter("id");
		condMap.put("id", id);
		ApiResponse<Object> apiResponseDb = this.usersDbService.deleteOneCartService(condMap);
		
		String path = "/head/UsersHeadServlet?method=cartList";
		response.sendRedirect(request.getContextPath() + path);
	}
	
	/**
	 * 打开博客页面
	 * @param request
	 * @param response
	 */
	public void blogInsert(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		/* 页面跳转 */
		String path = "/head/users/blogInsert" ; 
		/* 页面跳转 */
		path = this.prefix + path + this.subfix; 
		request.getRequestDispatcher(path).forward(request, response);
	}
	
	/**
	 * 博客提交
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void blogInsertSubmit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		MakeupUsers users = (MakeupUsers) this.findObjfromSession(request, "users");
		
		MakeupBlog blog = new MakeupBlog();
		/* 创建对象 */
		blog.setUsersId(users.getId());
		blog.setStatus(MakeupBlogEnum.STATUS_ENABLE.getStatus());
		
		String name = request.getParameter("name");
		String content = request.getParameter("content");
		blog.setName(name);
		blog.setContent(content);
		
		ApiResponse<Object> apiResponseDb = this.usersDbService.saveOneBlogService(blog);
		if(apiResponseDb.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus())
		{
			String path = "/IndexHeadServlet?method=blogList"; 
			response.sendRedirect(request.getContextPath() + path);
			return ; 
		}
		this.blogInsert(request,response);
	}
	
	/**
	 * 博客更新
	 * @param request
	 * @param response
	 */
	public void blogUpdateSubmit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		/* 准备路径 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		
		String id = request.getParameter("id");
		/* 按照id查询 */
		condMap.put("id", id);
		ApiResponse<MakeupBlog> apiResponse = this.usersDbService.findOneBlogService(condMap);
		request.setAttribute("response", apiResponse.toJSON());
		
		MakeupBlog blog = apiResponse.getDataOneJava() ; 
		
		boolean updateFlag = false ; 
		/* 接收参数 */
		String operType = request.getParameter("operType");
		if("update".equalsIgnoreCase(operType))
		{
			String name = request.getParameter("name");
			String content = request.getParameter("content");
			blog.setName(name);
			blog.setContent(content);
			
			/* 博客更新 */
			updateFlag = true ; 
		}else if("up".equalsIgnoreCase(operType))
		{
			/* 博客顶 */
			blog.setUpNum(blog.getUpNum() + 1);
			/* 博客更新 */
			updateFlag = true ; 
		}else if("down".equalsIgnoreCase(operType))
		{
			/* 博客踩 */
			blog.setDownNum(blog.getDownNum() + 1);
			/* 博客更新 */
			updateFlag = true ; 
		}
		
		if(updateFlag)
		{
			ApiResponse<Object> apiResponseDb = this.usersDbService.updateOneBlogService(blog);
			ConstatFinalUtil.SYS_LOGGER.info("更新结果:{}",apiResponseDb.toJSON().toJSONString());
		}
		
		String path = "/IndexHeadServlet?method=blogUpdate&id=" + id ; 
		response.sendRedirect(request.getContextPath() + path ) ;
	}
	
	public void logout(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("=====logout=====");
		/* 从session中移除数据 */
		HttpSession session = request.getSession() ;
		session.removeAttribute("users");
		String path = "/NoLoginServlet?method=login"; 
		response.sendRedirect(request.getContextPath() + path ) ;
	}
}
